package com.zzjson.zk.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryOneTime;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

/**
 * <p>****************************************************************************</p>
 * <p><b>Copyright © 2010-2020 shuncom team All Rights Reserved<b></p>
 * <ul style="margin:15px;">
 * <li>Description : com.zzjson.zk.curator</li>
 * <li>Version     : 1.0.0</li>
 * <li>Creation    : 2020年03月28日</li>
 * <li>@author     : zzy0_0</li>
 * </ul>
 * <p>****************************************************************************</p>
 */
public class CuratorDemo {
	public static CuratorFramework curatorFramework;

	public static void main(String[] args) throws Exception {
		CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
		builder.connectString("116.62.221.6:2181");
		builder.retryPolicy(new RetryOneTime(1));
		CuratorFramework build = builder.build();
		curatorFramework = build;
		build.start();
		// create();
		// update();
		// deleteWithVersion();
		deleteData();

	}

	public static void create() throws Exception {
		curatorFramework.create().
				creatingParentsIfNeeded().
				withMode(CreateMode.PERSISTENT).
				forPath("/test/dd", "hello".getBytes());
	}


	public static void update() throws Exception {
		curatorFramework.setData().forPath("/test/dd", "update".getBytes());
	}

	public static void get() throws Exception {
		byte[] bytes = curatorFramework.getData().forPath("/test/dd");
		System.out.println(new String(bytes));
	}

	public static void deleteWithVersion() throws Exception {
		curatorFramework.delete().withVersion(0).forPath("/test/dd");
	}

	public static void deleteData() throws Exception {
		Stat stat = new Stat();
		byte[] bytes = curatorFramework.getData().storingStatIn(stat).forPath("/test/dd");
		String value = new String(bytes);
		curatorFramework.delete().withVersion(stat.getVersion()).forPath("/test/dd");
	}
}
